<template>
  <div class="app-main pet-container">
    <el-card shadow="never">
      <el-row>
        <el-form :inline="true" :model="queryForm" ref="queryForm">
          <el-form-item label="宠物种类" prop="type">
            <el-select v-model="queryForm.type" clearable placeholder="请选择宠物种类">
              <el-option v-for="item in petTypeArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryData">查询</el-button>
            <el-button @click="resetForm('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <el-button type="primary" plain icon="el-icon-plus" @click="addShow">新增</el-button>
      </el-row>
      <el-row class="table-container">
        <el-table :data="tableData" v-loading="loading" element-loading-text="数据加载中···" stripe style="width: 100%" size="medium" max-height="630">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column label="宠物种类" prop="type" :formatter="typeRender" show-overflow-tooltip></el-table-column>
          <el-table-column label="宠物图片" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-image v-if="scope.row.image !== ''" style="width: 50px; height: 50px" :src="'/api' + scope.row.image" :preview-src-list="['/api' + scope.row.image]"></el-image>
              <span v-else>暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="宠物年龄" prop="age" show-overflow-tooltip></el-table-column>
          <el-table-column label="宠物性别" prop="sex" :formatter="sexRender" show-overflow-tooltip></el-table-column>
          <el-table-column label="是否接种" prop="vaccinate" :formatter="vaccinateRender" show-overflow-tooltip></el-table-column>
          <el-table-column label="宠物价格" prop="price" show-overflow-tooltip></el-table-column>
          <el-table-column label="库存数量" prop="stock" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="text" class="el-icon-edit" @click="updateShow(scope.row)">修改</el-button>
              <el-button type="text" class="el-icon-delete" @click="deleteShow(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <el-row class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNo"
          :page-sizes="page.pageSizes"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
        </el-pagination>
      </el-row>
    </el-card>
    <el-dialog :title="formTitle" :visible.sync="addFormVisible" width="600px" :close-on-click-modal="closeModal">
      <el-form :model="addForm" :rules="rules" ref="addForm" label-width="90px">
        <el-form-item label="宠物种类" prop="type">
          <el-select v-model="addForm.type" clearable placeholder="请选择宠物种类" style="width: 100%">
            <el-option v-for="item in petTypeArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物图片" prop="image">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="addForm.imageUrl" :src="addForm.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="宠物年龄" prop="age">
          <el-input v-model="addForm.age" placeholder="请输入宠物年龄" clearable></el-input>
        </el-form-item>
        <el-form-item label="宠物性别" prop="sex">
          <el-select v-model="addForm.sex" placeholder="请选择宠物性别" clearable style="width: 100%">
            <el-option v-for="item in petGenderArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否接种" prop="vaccinate">
          <el-select v-model="addForm.vaccinate" placeholder="请选择是否接种" clearable style="width: 100%">
            <el-option v-for="item in vaccinateArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="宠物价格" prop="price">
          <el-input v-model="addForm.price" placeholder="请输入宠物价格" clearable></el-input>
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input v-model="addForm.stock" placeholder="请输入库存数量" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelForm('addForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addPet, deletePet, editPet, getPet} from "@/api/pet";
import {getToken} from '@/utils/token'

export default {
  name: "index",
  data() {
    return {
      petTypeArr: [
        {'label': '猫', 'value': '1'},
        {'label': '狗', 'value': '2'},
        {'label': '仓鼠', 'value': '3'},
        {'label': '小猪', 'value': '4'},
        {'label': '兔子', 'value': '5'},
        {'label': '羊驼', 'value': '6'},
        {'label': '鹦鹉', 'value': '7'},
        {'label': '鸽子', 'value': '8'},
        {'label': '乌龟', 'value': '9'},
        {'label': '蝈蝈', 'value': '10'},
        {'label': '金鱼', 'value': '11'},
        {'label': '桑蚕', 'value': '12'},
      ],
      petGenderArr: [
        {'label': '公', 'value': 1},
        {'label': '母', 'value': 2}
      ],
      vaccinateArr: [
        {'label': '是', 'value': 1},
        {'label': '否', 'value': 0}
      ],
      queryForm: {
        type: ''
      },
      loading: false,
      tableData: [],
      page: {
        pageNo: 1,
        pageSizes: [10, 50, 100, 200, 500],
        pageSize: 10,
        total: 5
      },
      addFormVisible: false,
      formTitle: '新增',
      addForm: {
        id: '',
        type: '',
        image: '',
        imageUrl: '',
        age: '',
        sex: '',
        vaccinate: '',
        price: '',
        stock: ''
      },
      rules: {
        type: [
          {required: true, message: '请选择宠物种类', trigger: 'change'},
        ],
        image: [
          {required: true, message: '请选择宠物图片', trigger: 'change'},
        ],
        price: [
          {required: true, message: '请输入宠物价格', trigger: 'change'},
        ],
        stock: [
          {required: true, message: '请输入库存数量', trigger: 'change'},
        ]
      },
      closeModal: false,
      uploadUrl: '/api/system/common/upload',
      uploadHeaders: {
        Authorization: getToken()
      }
    }
  },
  created() {
    this.queryData()
  },
  methods: {
    typeRender(data) {
      for(let i=0; this.petTypeArr.length; i++) {
        if(data.type === this.petTypeArr[i].value) {
          return this.petTypeArr[i].label
        }
      }
    },
    sexRender(data) {
      if(data.sex === 1) {
        return '公'
      } else if (data.sex === 2) {
        return '母'
      }
    },
    vaccinateRender(data) {
      if(data.vaccinate === 1) {
        return '是'
      } else {
        return '否'
      }
    },
    queryData() {
      this.loading = true
      let params = {
        type: this.queryForm.type,
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize
      }
      getPet(params).then(response => {
        if(response.code === 200) {
          this.tableData = response.data.list
          this.page.total = response.data.total
        } else {
          this.$message.error(response.msg);
        }
        this.loading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.queryData()
    },
    handleAvatarSuccess(res) {
      // console.log(res, '上传结果')
      this.addForm.image = res.fileName
      this.addForm.imageUrl = res.url;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPng = file.type === 'image/png';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG && !isPng) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!');
      }
    },
    addShow() {
      this.formTitle = '新增'
      this.addForm.type = ''
      this.addForm.image = ''
      this.addForm.imageUrl = ''
      this.addForm.age = ''
      this.addForm.sex = ''
      this.addForm.vaccinate = ''
      this.addForm.price = ''
      this.addForm.stock = ''
      this.addFormVisible = true
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.addForm.id !== '') {
            let params = {
              id: this.addForm.id,
              type: this.addForm.type,
              image: this.addForm.image,
              age: this.addForm.age,
              sex: this.addForm.sex,
              vaccinate: this.addForm.vaccinate,
              price: this.addForm.price,
              stock: this.addForm.stock,
            }
            editPet(params).then(response => {
              if(response.code === 200){
                this.$message({
                  message: response.msg,
                  type: 'success'
                });
              } else {
                this.$message({
                  message: response.msg,
                  type: 'error'
                });
              }
              this.addFormVisible = false
              this.queryData()
            })
          } else {
            let params = {
              type: this.addForm.type,
              image: this.addForm.image,
              age: this.addForm.age,
              sex: this.addForm.sex,
              vaccinate: this.addForm.vaccinate,
              price: this.addForm.price,
              stock: this.addForm.stock,
            }
            addPet(params).then(response => {
              if(response.code === 200){
                this.$message({
                  message: response.msg,
                  type: 'success'
                });
              } else {
                this.$message({
                  message: response.msg,
                  type: 'error'
                });
              }
              this.addFormVisible = false
              this.queryData()
            })
          }
        } else {
          return false;
        }
      });
    },
    cancelForm(formName) {
      this.$refs[formName].resetFields();
      this.addFormVisible = false
    },
    updateShow(row) {
      this.formTitle = '修改'
      this.addForm.id = row.id
      this.addForm.type = row.type
      this.addForm.image = row.image
      this.addForm.age = row.age
      this.addForm.sex = row.sex
      this.addForm.vaccinate = row.vaccinate
      this.addForm.price = row.price
      this.addForm.stock = row.stock
      this.addFormVisible = true
    },
    deleteShow(row) {
      this.$confirm('是否确认删除选中的数据项？').then(function() {
        return deletePet(row.id)
      }).then((response) => {
        if(response.code === 200){
          this.$message({
            message: response.msg,
            type: 'success'
          });
        } else {
          this.$message({
            message: response.msg,
            type: 'error'
          });
        }
        this.queryData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      })
    },
    handleSizeChange(val) {
      this.page.pageSize = val
      this.page.pageNo = 1
      this.queryData()
    },
    handleCurrentChange(val) {
      this.page.pageNo = val
      this.queryData()
    }
  }
}
</script>

<style>
.pet-container .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.pet-container .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.pet-container .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.pet-container .avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>

<style lang="scss" scoped>
.app-main {
  padding: 20px;
  box-sizing: border-box;

  .table-container {
    margin-top: 20px;
  }

  .pagination-container {
    margin: 20px 0;
    float: right;
  }
}
</style>
